
//通用接口
module.exports = app => {
  const express = require('express');
  const admin = express.Router({
    //表示合并参数
    mergeParams: true
  });
  //创建资源
  admin.post('/', async (req, res) => {
    const model = await req.Model.create(req.body);
    res.send(model)
  });
  //更新资源
  admin.put('/:id', async (req, res) => {
    const model = await req.Model.findByIdAndUpdate(req.params.id, req.body)
    res.send(model)
  });
  //删除资源
  admin.delete('/:id', async (req, res) => {
    await req.Model.findByIdAndDelete(req.params.id);
    res.send({
      success: true
    })
  });
  //资源列表
  admin.get('/', async (req, res) => {
    const queryOptions = {};
    if (req.Model.modelName === 'Category') {
      queryOptions.populate = 'parent'
    }
    const items = await req.Model.find().setOptions(queryOptions).limit(10);
    res.send(items);
  });

  //资源详情
  admin.get('/:id', async (req, res) => {
    const model = await req.Model.findById(req.params.id)
    res.send(model)
  });

  app.use('/admin/api/:resource', async (req, res, next) => {
    const modelName = require('inflection').classify(req.params.resource);
    req.Model = require(`../models/${modelName}`);
    next()
  }, admin)
  // const Category = require('../models/Category')

  const multer = require('multer');
  //接受文件的地址
  const upload = multer({dest: __dirname + '/../uploads'});
  //允许接受文件
  app.post('/admin/upload', upload.single('file'), async (req, res) => {
    const file = req.file;
    //给文件配置一个url
    file.url = `http://localhost:3000/uploads/${file.filename}`
    res.send(file)
  })

  app.post('/admin/login', async (req, res)=> {
    // res.send('ok')
    //获得前端的数据，与数据库里面的数据进行比对
    const { username, password } = req.body;
    //进行数据库的信息查询和密码比对
    //1. 根据用户名找用户
    const AdminUser = require('../models/AdminUser');
    const user = await AdminUser.findOne({username}).select('+password');
    if(!user) {
      return res.status(422).send({
        message: '用户不存在'
      })
    }else {
      //2. 校验密码
      const bcrypt = require('bcryptjs');
      const isValid = await bcrypt.compareSync(password, user.password);
      if(!isValid){ //比对失败
        return res.status(422).send({
          message: '密码错误'
        })
       }else{ //返回值不为空，密码比对成功
          //3. 返回token
        const jwt = require('jsonwebtoken');
        //token的生成
        const token = jwt.sign({_id: user._id}, app.get('secret'))
        res.send(token)
      }

    }

  })
}

